package com.qc31.monitorlib.ui.adapter

import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.qc31.comlib.entity.AlarmType
import com.qc31.monitorlib.R

/**
 *@Author Jasper
 *@Time   2020/10/19
 *@Desc   todo
 */
class ChooseAlarmAdapter :
    BaseQuickAdapter<AlarmType, BaseViewHolder>(R.layout.item_all_alarm_choose) {

    override fun convert(holder: BaseViewHolder, item: AlarmType) {
        item.run {
            val allChoose = holder.getView<TextView>(R.id.tvAllChoose)
            allChoose.text = name
            allChoose.isSelected = isAllChoose
            val recycler: RecyclerView = holder.getView(R.id.recyclerView)
            recycler.layoutManager = LinearLayoutManager(context)
            recycler.adapter = AlarmItemAdapter(children).apply {
                setOnItemClickListener { adapter, view, position ->
                    children[position].isChoose = !children[position].isChoose
                    isAllChoose = isAllChecked(children)
                    allChoose.isSelected = isAllChoose
                    notifyDataSetChanged()
                    chooseAllBack?.onChooseAll()
                }
            }
            allChoose.setOnClickListener {
                val list: MutableList<AlarmType.Children> = item.children
                item.isAllChoose = !item.isAllChoose
                for (children in list) {
                    children.isChoose = item.isAllChoose
                }
                notifyDataSetChanged()
                chooseAllBack?.onChooseAll()
            }
        }
    }


    private var chooseAllBack: ChooseAllBack? = null

    fun setAllBack(allBack: ChooseAllBack) {
        chooseAllBack = allBack
    }

    interface ChooseAllBack {
        fun onChooseAll()
    }

    private fun isAllChecked(childrens: MutableList<AlarmType.Children>): Boolean {
        for (children in childrens) {
            if (!children.isChoose) return false
        }
        return true
    }

    class AlarmItemAdapter(list: MutableList<AlarmType.Children>) :
        BaseQuickAdapter<AlarmType.Children, BaseViewHolder>(
            R.layout.item_alarm_choose,
            data = list
        ) {
        override fun convert(holder: BaseViewHolder, item: AlarmType.Children) {
            item.run {
                val textChildren = holder.getView<TextView>(R.id.tvItemAlarmChoose)
                textChildren.text = name
                textChildren.isSelected = isChoose
            }
        }

    }
}